package com.pi.pro.xcmg.am.was.fac.handler;


import com.pi.common.CodesConstants;
import com.pi.common.utils.TextUtils;
import com.pi.framework.core.controller.BaseCrudCustomHandler;
import com.pi.framework.core.exception.ApplicationException;
import com.pi.framework.core.util.DateUtils;
import com.pi.framework.core.util.SecurityUtils;
import com.pi.framework.core.util.StringUtils;
import com.pi.pro.xcmg.am.common.XcmgAmConstants;
import com.pi.pro.xcmg.am.common.vo.act.PalletizeChangeData;
import com.pi.pro.xcmg.am.was.fac.service.WasCustomWorkService;
import com.pi.wms.common.WmsConstants;
import com.pi.wms.dto.act.TaskActionDto;
import com.pi.wms.entity.*;
import com.pi.wms.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 */
public class KitAsnCustomHandler extends BaseCrudCustomHandler<TwaDocAsnHeader,Long> {


    @Autowired
    private MaterialService materialService;

    @Autowired
    private DivisionService divisionService;

    @Autowired
    private AsnService asnService;

    @Autowired
    private AsnDetailsService asnDetailsService;

    @Autowired
    private PalletizeService palletizeService;

    @Autowired
    private WasCustomWorkService wasCustomWorkService;

    @Autowired
    private TaskService taskService;

    private Map<Long, TwmBasMaterial> materials=new HashMap<>();


    @Override
    public String afterSave(Model model, TwaDocAsnHeader header, HttpServletRequest request, RedirectAttributes redirectAttributes) {
        String m = "";
        List<TwaDocAsnDetails> lines=null;
        if (header==null){
            return m;
        }
        if (header.getId()==null){
            return m;
        }
        if (!XcmgAmConstants.WORK_SOURCE_KIT.equalsIgnoreCase(header.getCategory())){
            return m;
        }
        TwaDocAsnDetails line=null;
        TwtActPalletizeList pal=null;
        PalletizeChangeData palletizeData=null;
        TaskActionDto actionDto=null;
        String batchnum=null;
        try{
            lines=this.asnDetailsService.findByDocumentId(header.getId());
            if ((lines!=null)&& (lines.size()>0)){
                return m;
            }
            batchnum= TextUtils.genBatchNumber();
            line=this.createAsnDetails(header);
            if (line!=null){
                this.asnDetailsService.save(line);
            }
            palletizeData=this.translateTo(header, line);
            palletizeData.setBatchnumber(batchnum);
            actionDto=new TaskActionDto();
            actionDto.setWorker(SecurityUtils.getLoginUsername());
            pal =this.wasCustomWorkService.createPalletizeData(palletizeData, header, line, this.takeMaterial(), actionDto);
        }catch (Exception e){
            e.printStackTrace();
        }
        return m;
    }

    //DEL
    @Override
    public String beforeDelete(Long heaedrId, Model model, HttpServletRequest request, RedirectAttributes redirectAttributes){
        String m = "";
        if (heaedrId==null){
            return m;
        }

        TwaDocAsnHeader header=null;
        List<TwaDocAsnDetails> lines=null;
        List<TwtActTaskList> tasks=null;
        List<TwtActPalletizeList> pals=null;
        try{
            header=this.asnService.findById(heaedrId);
            if (header==null){
                return m;
            }
            if (!WmsConstants.ASN_STATUS_CREATE.equalsIgnoreCase(header.getStatus())){
                throw new ApplicationException("入库单已经开始作业，不能删除.");
            }
            lines=this.asnDetailsService.findByDocumentId(heaedrId);
            if (lines!=null){
                for (TwaDocAsnDetails d:lines){
                    if (d==null){
                        continue;
                    }
                    if (!WmsConstants.ASN_STATUS_CREATE.equalsIgnoreCase(d.getLineStatus())){
                        throw new ApplicationException("入库单明细行已经开始作业，不能删除.");
                    }
                }
            }
            if (!StringUtils.isNullOrBlank(header.getDeliveryContainerNum())){
                tasks=this.taskService.queryWorkingTasks("", header.getDeliveryContainerNum().trim());
                if ((tasks!=null)&&(tasks.size()>0)){
                    throw new ApplicationException("码盘托盘已经生成任务，不能删除.托盘码:"+header.getDeliveryContainerNum()+",任务号:"+tasks.get(0).getNumber());
                }
            }
            pals=this.palletizeService.findByDocumentId(header.getId());
            this.palletizeService.delete(pals);
            this.asnDetailsService.delete(lines);
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    private TwaDocAsnDetails createAsnDetails(TwaDocAsnHeader header){
        TwaDocAsnDetails line=null;

        TwmBasMaterial mat=this.takeMaterial();
        line = new TwaDocAsnDetails();
        line.setHeaderId(header.getId());
        line.setLineNumber("0010");
        line.setLineStatus(WmsConstants.ASN_STATUS_CREATE);
        line.setRefDocNumber(header.getDeliveryShipNum());
        line.setRefLineNumber(null);
        line.setMaterialId(mat.getId());
        line.setMaterialCode(mat.getCode());
        line.setMaterialName(mat.getName());
        line.setQtyOrdered(BigDecimal.ONE);
        line.setQtyOrderedEach(line.getQtyOrdered());
        line.setQtyPalletized(BigDecimal.ONE);
        line.setQtyPalletizedEach(line.getQtyPalletized());
        line.setQtyReceived(BigDecimal.ZERO);
        line.setQtyReceivedEach(line.getQtyReceived());
        line.setQtyRejected(BigDecimal.ZERO);
        line.setQtyReceivedEach(line.getQtyRejected());
        line.setPackId(mat.getPackId());
        line.setUomCode(mat.getReceiveUom());
        line.setContainNumber(header.getDeliveryContainerNum());
        line.setTraceNumber(line.getContainNumber());
        line.setOverReceiveFlag(CodesConstants.COMMON_FLAG_NO);
        line.setReceiveLocId(null);
        line.setPlantoLocId(null);

        line.setTotalPrice(null);
        line.setTotalCubic(null);
        line.setTotalGrossweight(null);
        line.setTotalNetweight(null);
        line.setProductStatus(null);
        line.setProductStatusDescr(null);
        line.setReleaseStatus(CodesConstants.COMMON_RELEASE_STATUS_CREATED);
        line.setReserveStatus(CodesConstants.COMMON_STATUS_CREATED);
        line.setFirstReceiveTime(null);
        line.setLastReceiveTime(null);
        line.setLotattr01(null);
        line.setLotattr02(null);
        line.setLotattr03(null);
        line.setLotattr04(null);
        line.setLotattr05(DateUtils.format(new Date(), "yyyy"));
        line.setLotattr06(null);
        line.setLotattr07(null);
        line.setLotattr08(null);
        line.setLotattr09(null);
        line.setLotattr10(null);
        line.setLotattr11(null);
        line.setLotattr12(null);
        line.setLotattr13(null);
        line.setLotattr14(null);
        line.setLotattr15(null);
        line.setLotattr16(null);

        line.setUdf01(null);
        line.setUdf02(null);
        line.setUdf03(null);
        line.setUdf04(null);
        line.setUdf05(null);
        line.setUdf06(null);
        line.setUdf07(null);
        line.setUdf08(null);
        line.setUdf09(null);
        line.setUdf10(null);
        line.setDEdi01(null);
        line.setDEdi02(null);
        line.setDEdi03(null);
        line.setDEdi04(null);
        line.setDEdi05(null);
        line.setDEdi06(null);
        line.setDEdi07(null);
        line.setDEdi08(null);
        line.setDEdi09(null);
        line.setDEdi10(null);
        line.setDEdi11(null);
        line.setDEdi12(null);
        line.setDEdi13(null);
        line.setDEdi14(null);
        line.setDEdi15(null);
        line.setDEdi16(null);
        line.setDEdi17(null);
        line.setDEdi18(null);
        line.setDEdi19(null);
        line.setDEdi20(null);
        line.setDelFlag(false);
        line.setNotes(null);
        line.setCreatedDate(new Date());
        line.setCreatedBy(header.getCreatedBy());
        line.setLastModifiedDate(line.getCreatedDate());
        line.setLastModifiedBy(line.getCreatedBy());

        return line;
    }

    private PalletizeChangeData translateTo(TwaDocAsnHeader header, TwaDocAsnDetails line){
        PalletizeChangeData palletizeData=new PalletizeChangeData();
        palletizeData.setDivisioncode(this.divisionService.retrieve(header.getDivisionId()));
        palletizeData.setCreatesource(CodesConstants.SYSTEM_WMS);

        palletizeData.setCustomercode(XcmgAmConstants.CUSTOMER_CODE_XCMG_AM);
        palletizeData.setMaterialcode(line.getMaterialCode());
        palletizeData.setQuantity(line.getQtyOrdered());
        palletizeData.setContainnumber(header.getDeliveryContainerNum());
        palletizeData.setTracenumber(palletizeData.getContainnumber());
        palletizeData.setCreatetype(header.getCategory());
        palletizeData.setLotattr05(line.getLotattr05());
        palletizeData.setReservenumber(null);
        palletizeData.setLotattr06(null);
        palletizeData.setLotattr07(null);
        palletizeData.setUdf01(header.getUdf01());
        palletizeData.setUdf02(header.getUdf02());
        palletizeData.setUdf03(header.getUdf03());
        palletizeData.setUdf04(header.getUdf04());
        palletizeData.setUdf05(header.getUdf05());
        palletizeData.setUdf06(header.getUdf06());
        palletizeData.setUdf07(header.getUdf07());
        palletizeData.setUdf08(header.getUdf08());
        palletizeData.setUdf09(header.getUdf09());
        palletizeData.setUdf10(header.getUdf10());
        palletizeData.setLocationcode(XcmgAmConstants.LOCATION_CODE_PA0101);
        return palletizeData;
    }

    private TwmBasMaterial takeMaterial(){
        TwmBasMaterial mat=this.materials.get(XcmgAmConstants.MATERIAL_ID_KIT);
        if (mat==null){
            mat=this.materialService.lookup(XcmgAmConstants.MATERIAL_ID_KIT);
            if (mat!=null){
                materials.put(mat.getId(), mat);
            }
        }
        return mat;
    }
}
